package com.zqxq.util;

import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.zqxq.dataprovider.normalDataProvider;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

//import net.sf.json.JSONObject;

/**
 * 基础类
 * 根据项目接口使用的协议，实现相关的请求
 *目前post请求只是表单方式提交
 */


public class HttpClientHelper 
{
	static String responseBody;
	private static String HEADER_CHANNEL = "XM";
	private static String HEADER_IMEI = "868029020964425";
	private static String HEADER_APP_VERSION = "1.2.2";
	private static String HEADER_APP_KEY = "ZQXQ-DQK";
	private static String HEADER_APP_SOURCE = "1";
	private static String HEADER_PUBLIC_KEY = "040CD66A84025B94CEAC3EC1B49C92D0";
	static CloseableHttpClient httpclient = HttpClients.createDefault();
		
	public static JsonObject getJSONObjectByPost(String url,List<NameValuePair> data,String signstr,String timestamp)  
    {
		
		HttpPost httppost = new HttpPost(url);
		CloseableHttpResponse response = null;
		JsonObject jsonResult = null;
		
        try 
        {
        	
        	//组装header
        	httppost.addHeader("public_key", HEADER_PUBLIC_KEY);
        	httppost.addHeader("app_key",HEADER_APP_KEY);
        	httppost.addHeader("source",HEADER_APP_SOURCE);
        	httppost.addHeader("client_id",HEADER_IMEI);
        	httppost.addHeader("channel",HEADER_CHANNEL);
        	httppost.addHeader("app_version",HEADER_APP_VERSION);        	
        	httppost.addHeader("timestamp",timestamp);
        	httppost.addHeader("signature",signstr);        	
        	        	
        	//组装请求Entity
        	UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(data);
        	//UrlEncodedFormEntity类创建的对象可以模拟传统的HTML表单传送POST请求中的参数
        	httppost.setEntity(formEntity);   
        	//获取返回内容
        	response = httpclient.execute(httppost);
        	
        	//获取状态值，当状态值为200时，继续执行
	    	int status = response.getStatusLine().getStatusCode();
	    	if (status == 200) {
	    		//获取内容，并转换成String类型
	    		HttpEntity entity = response.getEntity();	       
	    		responseBody = EntityUtils.toString(entity,"UTF-8");	    		
	    		//转换成json格式，方便后面做验证
	    		jsonResult = new Gson().fromJson(responseBody, JsonObject.class);
 	       		//jsonResult =JsonObject.fromObject(responseBody); 	                  
	    	} 
	    	else {
	    		System.out.print("请求错误，状态码为：" + response.getStatusLine().getStatusCode());
	    		throw new ClientProtocolException("意外的状态返回: " + status);
	    	} 
	    }catch(Exception e){  
            e.printStackTrace();  
        }  
	    finally {
	    	try{  
                if(response != null)  
                    response.close();                  
            }catch(IOException e){  
                e.printStackTrace();  
            }	    	
	    }
		return jsonResult;
    }
	
	

	public static JsonObject getJSONObjectByGet(String url) 
	{
				
        HttpGet httpget = new HttpGet(url);		
		CloseableHttpResponse response = null;
		JsonObject jsonResult = null;
		
	    try {
	    	//执行GET请求，获取返回内容
	    	response = httpclient.execute(httpget);
	    	int status = response.getStatusLine().getStatusCode();
	    	if (status == 200) {
	    	//获取内容，并转换成String类型
	    	HttpEntity entity = response.getEntity();	       
	    	responseBody = EntityUtils.toString(entity);	    	
	    	//转换成json格式，方便后面做验证
	    	//jsonResult = JsonObject.fromObject(responseBody); 
	    	jsonResult = new Gson().fromJson(responseBody, JsonObject.class); 	                  
	     } 
	    else {
	        System.out.print("请求错误，状态码为：" + response.getStatusLine().getStatusCode());
	        throw new ClientProtocolException("意外的状态返回: " + status);
	     } 
	    }catch(Exception e){  
            e.printStackTrace();  
        }
	    finally {
	    	try{  
                if(response != null)  
                    response.close();                  
            }catch(IOException e){  
                e.printStackTrace();  
            }
	    }
	    return jsonResult;
	
	}
	
	
	
	public static void closeClient() throws IOException 
	{
		httpclient.close();
	}

	
	@SuppressWarnings("finally")
	public static HttpClient Login(HttpClientHelper httphelper) {
		
		String url= normalDataProvider.getLoginUrl();
		String phone= normalDataProvider.getPhone();
		String passwd= normalDataProvider.getPasswd();
		String timestamp = null;
		String signstr = null;
		HttpPost httppost = new HttpPost(url);	
		List<NameValuePair> data = new ArrayList<NameValuePair>();
        data.add(new BasicNameValuePair("phone", phone));
        data.add(new BasicNameValuePair("login_pwd", passwd));
        try {
        //请求实体排序
        paramSort ps = new paramSort();
        String paramsort = ps.sortParam(data);
        //生成签名
        Signature sign = new Signature();
        Map<String, String> signstrlogin = sign.signatureBuild(paramsort);
        signstr = signstrlogin.get("signature");
        timestamp = signstrlogin.get("timestamp");	
        //组装header
        httppost.addHeader("public_key", HEADER_PUBLIC_KEY);
        httppost.addHeader("app_key",HEADER_APP_KEY);
        httppost.addHeader("source",HEADER_APP_SOURCE);
        httppost.addHeader("client_id",HEADER_IMEI);
        httppost.addHeader("channel",HEADER_CHANNEL);
        httppost.addHeader("app_version",HEADER_APP_VERSION);        	
        httppost.addHeader("timestamp",timestamp);
        httppost.addHeader("signature",signstr);       	
        //组装请求Entity
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(data);
        //UrlEncodedFormEntity类创建的对象可以模拟传统的HTML表单传送POST请求中的参数
        httppost.setEntity(formEntity);
        }catch(Exception e){  
            e.printStackTrace();  
        }
	    finally {
	    	return httpclient;
	    }
		 	 	     
		
	}

	
}
